//
//  CourseVC.swift
//  Auscultation
//
//  Created by 张文博 on 2021/3/19.
//

import UIKit

class CourseVC: BaseVC {
    var studayComlete = 0
    
    var exam = 0
    
    var pageNum: Int = 1
    var pageSize: Int = 10
    var studyDataArray: [CourseStudyModel?] = []
    var courseDataArray: [HomeCourseModel?] = []

    lazy var navSearchBtn: UIButton = {
        let navSearchBtn = UIButton()
        navView.addSubview(navSearchBtn)
        navSearchBtn.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-15)
            make.height.width.equalTo(40)
            make.width.equalTo(40)
        }
        navSearchBtn.addTarget(self, action: #selector(CourseVC.searchClick(btn:)), for: .touchUpInside)
        return navSearchBtn
    }()

    let headerView = CourseHeaderView(frame: CGRect(x: 0, y: 0, width: UIDevice.lgf_ScreenW, height: 280 - 65))

    lazy var navTitleL: UILabel = {
        let navTitleL = UILabel()
        navTitleL.font = UIFont.boldSystemFont(ofSize: 24)
        navTitleL.textColor = .white
        navView.addSubview(navTitleL)

        navTitleL.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(15)
            make.height.equalTo(29)
        }

        return navTitleL
    }()
    
    lazy var navLVL: UILabel = {
        let navLVL = UILabel()
        navLVL.font = UIFont.boldSystemFont(ofSize: 10)
        navLVL.textColor = UIColor(red: 123.0/255.0, green: 184.0/255.0, blue: 160.0/255.0, alpha: 1.0)
        navView.addSubview(navLVL)
        navLVL.snp.makeConstraints { (make) in
            make.left.equalTo(navTitleL.snp.right).offset(2)
            make.bottom.equalTo(navTitleL.snp.bottom).offset(0)
            make.height.equalTo(12)
        }


        navLVL.layer.cornerRadius = 3
//        let attrString = NSMutableAttributedString(string: "Lv3")
//        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 10),.foregroundColor: UIColor(red: 0.33, green: 0.67, blue: 0.75, alpha: 1)]
//        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
//        navLVL.attributedText = attrString
        navLVL.backgroundColor = .yellow
        return navLVL
    }()



    lazy var navView: UIView = {
        let navView = UIView()
        
        return navView
    }()

    lazy var table: UITableView = {
        let table = UITableView(frame: .zero, style: .grouped)
        view.addSubview(table)
        table.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(UIDevice.lgf_NavBarH())
        }
        table.delegate = self
        table.dataSource = self
        table.register(UINib.init(nibName: "RecomcCourseCell", bundle: Bundle.main), forCellReuseIdentifier: "RecomcCourseCell")
        table.register(StudyPainTableCell.self, forCellReuseIdentifier: "StudyPainTableCell")
        table.separatorStyle = .none
        table.backgroundColor = .clear
        return table
    }()

    

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)

    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ReloadTzbzshVC"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(studyComplete), name: NSNotification.Name(rawValue: "ReloadTzbzshVC"), object: nil)
        initUI()
    }
    
    @objc func studyComplete(){
        
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadStudyData()
        getdayData()
        loadCourseData()

        if self.exam == 0 {
//            let vc = WebVC()
//            vc.titleString = model.title
//            vc.url = model.filePath
//            self.navigationController?.pushViewController(vc, animated: true)

            
        }else{
            
        }
    }
    

}

// UI
extension CourseVC {

    func initUI() {

        let image_view1 = UIImageView(image: UIImage.init(named: "course_topbg"))
        image_view1.isUserInteractionEnabled = true
        view.addSubview(image_view1)
        image_view1.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(150)
        }
        view.addSubview(navView)
        navView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(44)
            make.top.equalTo(UIDevice.lgf_IsIphoneX() ? 44 : 20)
        }
        
        table.tableHeaderView = headerView
        guard let name = EWEUser.lgf.loginName else { return  }
        navTitleL.text = "Hi " + name.prefix(3) + "****"  + name.suffix(3)

        navLVL.text = "LV" + EWEUser.lgf.eduLevel
        navSearchBtn.setImage(UIImage(named: "home_search"), for: .normal)
        navSearchBtn.isHidden = true
        headerView.startStudyClickClouse = {

            print("kaishi")
        }
        
        table.mj_header = MJRefreshNormalHeader.init(refreshingBlock: { [weak self] in
            self?.pageNum = 1
            self?.loadCourseData()
            self?.loadStudyData()
            self?.getdayData()

        })
        
        table.mj_footer = MJRefreshBackNormalFooter.init(refreshingBlock: {
            [weak self] in
            self?.pageNum += 1
            self?.loadCourseData()

        })
        
        headerView.btnClickClouse = { [weak self] imageTitleView  in
            print(imageTitleView)
            switch imageTitleView.lgf_Name {
            case "公开课程":
                SVProgressHUD.showMessage("敬请期待")
                print("公开课程")
            case "名医直播":
                print("名医直播")
                SVProgressHUD.showMessage("敬请期待")

            case "一起学习":
                print("一起学习")
                SVProgressHUD.showMessage("敬请期待")

            case "成长路径":
                print("成长路径")
                SVProgressHUD.showMessage("敬请期待")
            case "等级评测":
                print("等级评测")
                self?.navigationController?.pushViewController(TestVC(), animated: true)
            default:
                break
            }
            
        }

    }
    
}

extension CourseVC{
    @objc func searchClick(btn:UIButton){
        print("搜索")
    }
}

extension CourseVC : UITableViewDelegate, UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
        return courseDataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "StudyPainTableCell") as! StudyPainTableCell
            cell.studyDataArray = studyDataArray
            return cell

        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "RecomcCourseCell") as! RecomcCourseCell
            guard let model = courseDataArray[indexPath.row] else { return cell }
            cell.model = model
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let model = courseDataArray[indexPath.row] else { return }
        let vc = WebVC()
        vc.titleString = model.title
        vc.url = model.filePath
        
        self.navigationController?.pushViewController(vc, animated: true)

    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 270
        }
        return 100
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        return 0.0001
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let head = CourseSectionHeadView()
        if section == 0 {
            head.sectionTitleL.text = "当前学习计划"
            head.sectionMore.isHidden = false
            head.sectionMore.addTarget(self, action: #selector(moreClick), for: .touchUpInside)
            
        }else{
            head.sectionTitleL.text = "推荐课程"
            head.sectionMore.isHidden = true

        }
        return head
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footer = UIView()
        footer.backgroundColor = .white
        return footer
    }
}


// MARK: - 请求
extension CourseVC{

    func loadStudyData() {
        
        let paramet  = [
            "pageNo" : "1",
            "pageSize" : "10"
        ]
        EWERequest.lgf("3dStudy", paramet, .get) { [weak self] (data) in
            guard let result = (data["result"] as? [Any]?) else { return  }
            self?.studyDataArray.removeAll()
            let arr = Array<CourseStudyModel>.deserialize(from: result)
            self?.studyDataArray += arr ?? []
            self?.table.reloadData()
            
        } _: {  (error) in
            SVProgressHUD.showError(error)
        }

    }
    
    func getdayData() {
        EWERequest.lgf("login", [:], .get) { (data) in
           
            guard let result = (data as? [String: Any]) else { return  }
            guard let clock = result["clock"] else { return  }
            guard let time = result["time"] else { return  }
            guard let exam = result["exam"] else { return  }
            self.exam = exam as! Int
            
            self.headerView.todayStudyVL.attributedText = changeFontColor(totalString: "\(time)" + "分钟", subString: "分钟", font: UIFont.boldSystemFont(ofSize: 14), textColor: UIColor.black)
            self.headerView.punchcardVL.attributedText = changeFontColor(totalString: "\(clock)" + "天", subString: "天", font: UIFont.boldSystemFont(ofSize: 14), textColor: UIColor.black)

        } _: { [weak self] (error) in
            
            SVProgressHUD.showError(error)
        }
    }
    
    func loadCourseData() {
        let paramet  = [
            "pageNo" : pageNum.description,
            "pageSize" : pageSize.description
        ]
        EWERequest.lgf("course", paramet, .get) {  (data) in
            guard let result = (data["result"] as? [Any]?) else { return  }
            if self.pageNum == 1 {
                self.courseDataArray.removeAll()
                self.table.mj_header?.endRefreshing()
            }
            
            let arr = Array<HomeCourseModel>.deserialize(from: result)
            if arr?.count == 0 {
                self.table.mj_footer?.endRefreshingWithNoMoreData()
            }else{
                self.table.mj_footer?.endRefreshing()
            }
            self.courseDataArray += arr ?? []
            self.table.reloadData()
        } _: {  (error) in
            SVProgressHUD.showError(error)
        }

    }
    
   @objc func moreClick() {
        self.navigationController?.pushViewController(TPViewController(), animated: true)
    }
}
